/*
 * Copyright (C) 2015 yixun All Rights Reserved.
 *
 * AreaServiceImpl.java
 */
package com.yixun.qfbao.api.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.PascalNameFilter;
import com.yixun.qfbao.api.service.WHReportService;
import com.yixun.qfbao.config.WHApiConfig;
import com.yixun.qfbao.dao.ApiLogDao;
import com.yixun.qfbao.model.ApiLog;
import com.yixun.qfbao.model.dto.ApiLogDto;
import com.yixun.qfbao.model.whdto.ItemInfoDto;
import com.yixun.qfbao.model.whdto.SyncReportDto;
import com.yixun.qfbao.util.RestTemplateUtil;
import com.yixun.qfbao.xf.model.dto.CustomerPremisesDto;
import com.yixun.qfbao.xf.model.enums.ConfirmStatusEnum;
import com.yixun.qfbao.xf.model.enums.ReportTypeEnum;
import com.yixun.qfbao.xf.service.CustomerPremisesService;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.List;
import java.util.Objects;
import java.util.UUID;
import java.util.stream.Collectors;


@Service
public class WHReportServiceImpl implements WHReportService {

    private static Logger logger = LoggerFactory.getLogger(WHReportServiceImpl.class);

    @Autowired
    private WHApiConfig whApiConfig;
    @Autowired
    private ApiLogDao apiLogDao;
    @Autowired
    private CustomerPremisesService customerPremisesService;

    @Override
    public SyncReportDto sendWHSyncReport(List<Long> reportIds) {
        SyncReportDto syncReportDto = new SyncReportDto();
        if(!whApiConfig.isWhRequestSwitch()){
            logger.info("can not send report data to wh, because switch is closed------------->");
            return syncReportDto;
        }
        logger.info("send sync report data to wh start------------->");
        String timeStamp = String.valueOf(System.currentTimeMillis());
        String senid = UUID.randomUUID().toString().replaceAll("-", "");
        int count = reportIds.size();
        syncReportDto.setTimestamp(timeStamp);
        syncReportDto.setSenid(senid);
        syncReportDto.setCount(count);

        CustomerPremisesDto customerPremisesDto = new CustomerPremisesDto();
        customerPremisesDto.setReportIds(reportIds);
        List<ItemInfoDto> itemInfoDtoList = customerPremisesService.selectWHSyncReportList(customerPremisesDto);
        if(CollectionUtils.isNotEmpty(itemInfoDtoList)){
            itemInfoDtoList.forEach(item -> {
                if(StringUtils.isNotBlank(item.getReportType())){
                    item.setReportType(ReportTypeEnum.getDescByNo(item.getReportType()));
                }else {
                    item.setReportType(ReportTypeEnum.type_1.getDes());
                }
                if(StringUtils.isNotBlank(item.getStatus())){
                    item.setStatus(ConfirmStatusEnum.getDescByNo(item.getStatus()));
                }
            });
        }
        syncReportDto.setItemInfos(itemInfoDtoList);
        logger.info("report data, senid: {}, content: {}", senid, JSON.toJSONString(syncReportDto));

        String url = whApiConfig.getWhRequestUrl() + WHApiConfig.whGetBill;
        String resultMsg = RestTemplateUtil.sendHttpByJsonUpper(new RestTemplate(), url, syncReportDto, String.class, new HttpHeaders());

        // 简单记录操作日志.后续可通过此发送日志进行补发
        ApiLogDto apiLogDto = new ApiLogDto();
        apiLogDto.setUrl(url);
        apiLogDto.setOtherRelationId(JSON.toJSONString(reportIds));
        apiLogDto.setRequestContent(JSON.toJSONString(syncReportDto, new PascalNameFilter()));
        apiLogDto.setRemark(senid);
        apiLogDto.setResponseContent(resultMsg);
        apiLogDao.create(apiLogDto);

        logger.info("send sync report to wh result: {}", resultMsg);
        logger.info("send sync report data to wh end------------->");
        return syncReportDto;
    }

    @Override
    public void sendWHSyncReportAgain(List<Long> logIds) {
        if(CollectionUtils.isNotEmpty(logIds)){
            ApiLogDto apiLogDto = new ApiLogDto();
            apiLogDto.setLogIds(logIds);
            List<ApiLog> apiLogList = apiLogDao.selectListByDto(apiLogDto);
            if(CollectionUtils.isNotEmpty(apiLogList)){
                String url = whApiConfig.getWhRequestUrl() + WHApiConfig.whGetBill;
                apiLogList.forEach(item -> {
                    SyncReportDto syncReportDto = JSONObject.parseObject(item.getRequestContent(), SyncReportDto.class);
                    if(Objects.nonNull(syncReportDto)){
                        // 重置同步批次及时间
                        String timeStamp = String.valueOf(System.currentTimeMillis());
                        String sendId = UUID.randomUUID().toString().replaceAll("-", "");
                        syncReportDto.setTimestamp(timeStamp);
                        syncReportDto.setSenid(sendId);
                        String resultMsg = RestTemplateUtil.sendHttpByJson(new RestTemplate(), url, syncReportDto, String.class, new HttpHeaders());

                        // 简单记录操作日志.后续可通过此发送日志进行补发
                        List<ItemInfoDto> itemInfoDtoList = syncReportDto.getItemInfos();
                        List<Long> reportIds = itemInfoDtoList.stream().map(itemInfoDto -> Long.valueOf(itemInfoDto.getBillNo())).collect(Collectors.toList());
                        ApiLogDto createLogDto = new ApiLogDto();
                        createLogDto.setUrl(url);
                        createLogDto.setOtherRelationId(JSON.toJSONString(reportIds));
                        createLogDto.setRequestContent(JSON.toJSONString(syncReportDto));
                        createLogDto.setRemark(sendId);
                        createLogDto.setResponseContent(resultMsg);
                        apiLogDao.create(createLogDto);
                    }
                });
            }
        }

    }
}
